import React from "react";
import { Table } from "antd";
import { getProductList } from "@/api/product/product";
import { useEffect, useState, useRef } from "react";
import usePagination from "@/hooks/usePagination";
export default function Cart() {
  const [productList, setProductList] = useState([]);
  const flagRef = useRef(true);
  //获取商品列表中推荐的数据
  const getProductListDate = () => {
    getProductList().then((res) => {
      //显示推荐商品
      res.data.data = res.data.data.filter((item) => item.isrecommend === 1);
      // console.log(res.data.data);

      setProductList(res.data.data);
      //判断数据是否小于分页数，如果小于则不再请求数据 用于判断是否还有下一页
      if (
        res.data.data.length <=
        pagination.pageSize * (pagination.current - 1)
      ) {
        flagRef.current = false;
      }
    });
  };
  //组件挂载时获取数据
  useEffect(() => {
    getProductListDate();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  //使用usePagination自定义分页
  const pagination = usePagination({
    callback() {
      flagRef.current = true;
    },
  });

  const columns = [
    {
      title: "序号",
      width: 150,

      fixed: "left",
      render: (text, record, index) =>
        `${
          pagination.pageSize *
            (flagRef.current
              ? pagination.current - 1
              : pagination.current - 2) +
          index +
          1
        }`,
    },

    {
      /* Breakpoint = 'xxl' | 'xl' | 'lg' | 'md' | 'sm' | 'xs'; */
      title: "商品图片",

      dataIndex: "img1",
      render: (text, record, index) => {
        return (
          <img src={text} alt="" style={{ width: "50px", height: "50px" }} />
        );
      },
    },
    {
      title: "商品名称",
      responsive: ["xl"],
      ellipsis: true,
      // editable: true,
      dataIndex: "proname",
    },
    {
      title: "商品价格/元",
      editable: true,
      dataIndex: "originprice",
      sorter: (a, b) => a.originprice - b.originprice,
    },
    {
      title: "折扣",
      responsive: ["lg"],
      dataIndex: "discount",
    },
    {
      title: "销售额/元",
      responsive: ["lg"],
      dataIndex: "sales",
      sorter: (a, b) => a.sales - b.sales,
    },
    {
      title: "商品库存",
      editable: true,
      dataIndex: "stock",
    },
  ];
  return (
    <Table
      rowKey={(record) => record.proid}
      dataSource={productList}
      pagination={pagination}
      columns={columns}
    />
  );
}
